{include file="common/header" /}
<link rel="stylesheet" href="__LAYUIMINI__/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
<style>
    body {
        background-color: #ffffff;
    }
    .img-item {
        position: relative;
        width: 96px;
        height: 96px;
        border-radius: 6px;
        margin-bottom: 10px;
        margin-right: 10px;
    }
    .img-item img {
        border-radius: 6px;
        width: 100%;
        height: 100%;
    }
    .img-item i {
        font-size: 20px;
        position: absolute;
        top: -10px;
        right: -10px;
    }

    .submit-button{
        display: flex;
        position: fixed;
        bottom: 0;
        width: 100%;
        background: #fff;
        border-top: 1px solid #e6e6e6;
        padding: 12px 0;
        margin: 0;
        z-index: 1000;
    }
</style>
<!-- 图片剪切 -->
<script type="text/javascript" src="__STATIC__/js/cropper/js/jquery-1.11.3.min.js"></script>
<script src="__STATIC__/js/cropper/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>

<link rel="stylesheet" href="__STATIC__/js/cropper/css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="__STATIC__/js/cropper/css/cropper.css">
<link rel="stylesheet" href="__STATIC__/js/cropper/css/main.css">
<script src="__STATIC__/js/cropper/js/cropper.js"></script>

<body>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
  <legend>{$title}添加</legend>
</fieldset>
<div class="layui-form layuimini-form">
    
    <div class="layui-form-item">
        <label class="layui-form-label required">模型</label>
        <div class="layui-input-block col-sm-400" >
            <select name="moduleid">
                {volist name="$module_res" id="vo"}
                    <option value="{$vo.id}" {if $parent_moduleid /}  {if $vo.id == $parent_moduleid /} selected="" {/if}  {/if}  >{$vo.title}[{$vo.name}][{$vo.emptytable_name}]</option>
                {/volist}
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">父级</label>
        <div class="layui-input-block col-sm-400">
            <select name="parentid">
              <option value="">默认顶级</option>
                {volist name="$treeList" id="vo"}
                <option value="{$vo.id}" {if $vo.id == $parentid /} selected="" {/if}>{$vo.catname |raw}</option>
                {/volist}

            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">栏目标题</label>
        <div class="layui-input-block col-sm-400">
            <input type="text" class="layui-input" name="catname"  value="" autocomplete="off" placeholder="请输入栏目名称">
        </div>
    </div>

    <!-- <div class="layui-form-item">
        <label class="layui-form-label ">栏目副标题</label>
        <div class="layui-input-block col-sm-400">
            <input type="text" class="layui-input" name="catname1"  value="" autocomplete="off" placeholder="请输入栏目副标题">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label ">URL显示名称</label>
        <div class="layui-input-block col-sm-400">
            <input type="text" class="layui-input" name="htmlname"  value="" autocomplete="off" placeholder="请输入URL显示名称">
        </div>
    </div>
    
    <div class="layui-form-item">
        <label class="layui-form-label ">url链接</label>
        <div class="layui-input-block col-sm-400">
            <input type="text" class="layui-input" name="url"  value="" autocomplete="off" placeholder="请输入url链接">
        </div>
    </div>
    
    <div class="layui-form-item">
        <label class="layui-form-label ">分页数量</label>
        <div class="layui-input-block col-sm-400">
            <input type="text" class="layui-input" name="pagesize"  value="" autocomplete="off" placeholder="请输入分页数量，默认10">
        </div>
    </div> -->

    <div class="layui-form-item">
        <label class="layui-form-label ">缩略图</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="image_up">
              <i class="layui-icon layui-icon-upload"></i> 缩略图上传后剪切
            </button>（可上传{:config("webconfig")['cfg_upload_img_type']}格式，可上传大小{:config("webconfig")['cfg_max_img_size']/1024/1024}MB，建议上传尺寸：288*288）
            
            <div class="pic" id="image_show" style="margin-top:10px;">
                  
            </div>

        </div>
    </div>

    <!-- <div class="layui-form-item">
        <label class="layui-form-label ">小程序缩略图</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="image_up2">
              <i class="layui-icon layui-icon-upload"></i> 缩略图上传
            </button>
            
            <div class="pic" id="image_show2" style="margin-top:10px;">
                  
            </div>

        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label ">SEO标题</label>
        <div class="layui-input-block col-sm-400">
            <input type="number" name="title" autocomplete="off" class="layui-input" placeholder="请输入SEO标题">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label ">SEO关键字</label>
        <div class="layui-input-block col-sm-400">
            <input type="text" name="keywords" autocomplete="off" class="layui-input" placeholder="请输入SEO关键字">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label ">SEO描述</label>
        <div class="layui-input-block " ">
            <textarea name="description" style="width: 390px;height:100px;padding: 5px;border:1px solid #e6e6e6;"></textarea>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">是否导航</label>
        <div class="layui-input-block">
          <input type="radio" name="is_open" value="1" title="是" checked>
          <input type="radio" name="is_open" value="2" title="否">
        </div>
    </div>
-->
   <!--  <div class="layui-form-item">
        <label class="layui-form-label ">列表页模板</label>
        <div class="layui-input-block col-sm-400">
            <select name="template_list" lay-search>
                <option value="">直接选择或搜索选择</option>
                {volist name="files" id="vo"}
                <option value="{$vo}" >{$vo}</option>
                {/volist}
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label ">内容页模板</label>
        <div class="layui-input-block col-sm-400">
            <select name="template_show" lay-search>
                <option value="">直接选择或搜索选择</option>
                {volist name="files" id="vo"}
                <option value="{$vo}" >{$vo}</option>
                {/volist}
            </select>
        </div>
    </div> -->
 
    <div class="layui-form-item">
        <label class="layui-form-label ">排序</label>
        <div class="layui-input-block col-sm-400">
            <input type="text" class="layui-input" name="orderid"  value="{$sort}" autocomplete="off" placeholder="请输入排序">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <input type="hidden" name="act" value="add">
            <button class="layui-btn" lay-submit lay-filter="saveBtn">确认保存</button>

            <button class="layui-btn layui-btn-primary" onclick="javascript:history.go(-1)" >返回</button>
        </div>
    </div>
</div>


<div id="cropper_view" style="display: none;" >
<div class="container " >
    <div class="row" style="margin-top: 30px">
        <div class="col-md-9">
            <!-- <h3>Demo:</h3> -->
            <div class="img-container" style="width: 510px;height: 510px">
                <img id="cropper_image" src="__STATIC__/js/cropper/images/picture.jpg" style="display: none;" alt="Picture">
            </div>
        </div>
        <div class="col-md-3">
            <!-- <h3>Preview:</h3> -->
            <div class="docs-preview clearfix">
                <div class="img-preview" style="max-height:140px;max-width:260px;width: 260px;height: 140px"></div>
            </div>

            <div class="docs-data">

                <div class="input-group input-group-sm">
            <span class="input-group-prepend">
              <label class="input-group-text" for="dataWidth">宽</label>
            </span>
                    <input type="text" class="form-control" readonly id="dataWidth" placeholder="">
                    <span class="input-group-append">
              <span class="input-group-text">px</span>
            </span>
                </div>
                <div class="input-group input-group-sm">
            <span class="input-group-prepend">
              <label class="input-group-text" for="dataHeight">高</label>
            </span>
                    <input type="text" class="form-control" readonly id="dataHeight" placeholder="">
                    <span class="input-group-append">
              <span class="input-group-text">px</span>
            </span>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-9 docs-buttons">
            <!-- <h3>Toolbar:</h3> -->
            <!-- <div class="btn-group">
                <label class="btn btn-primary btn-upload" for="inputImage" title="Upload image file">
                    <input type="file" class="sr-only" id="inputImage" name="file" accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff">
                    <span class="docs-tooltip" data-toggle="tooltip" data-animation="false" title="">
              <span class="fa fa-upload">选择文件</span>
            </span>
                </label>
            </div> -->

            <div class="btn-group">
                <button type="button"  class="btn btn-primary" data-method="zoom" data-option="0.1" title="Zoom In">
            <span class="docs-tooltip" data-toggle="tooltip" data-animation="false" title="">
              <span class="fa fa-search-plus">放大</span>
            </span>
                </button>
                <button type="button"  class="btn btn-primary" data-method="zoom" data-option="-0.1" title="Zoom Out">
            <span class="docs-tooltip" data-toggle="tooltip" data-animation="false" title="">
              <span class="fa fa-search-minus">缩小</span>
            </span>
                </button>
            </div>

            <div class="btn-group">
                <button type="button"  class="btn btn-primary" data-method="getCroppedCanvas" data-option="" title="Crop">
            <span class="docs-tooltip" data-toggle="tooltip" data-animation="false" title="">
              <span class="fa fa-check">确认</span>
                <!-- <div class="progress">
                    <span class="bar"></span><span class="percent">0%</span >
               </div> -->
            </span>
                </button>

            </div>
        </div>
    </div>
</div>
</div>
<script>
    var uploadedImageName;
    var $image;
    var uploadedImageType;
    layui.use(['form','iconPickerFa','upload','laydate'], function () {
        var form = layui.form,
            iconPickerFa = layui.iconPickerFa,
            layer = layui.layer,
            upload = layui.upload,
            laydate = layui.laydate,
            $ = layui.$;

        laydate.render({
            elem: '#ID-laydate-demo'
        });

        window.imgdelete = function(dom){
            $(dom).parent().remove();
        }

        /*upload.render({
            elem: '#image_up'
            ,url: "{:url('Index/dyupload')}" 
            // ,multiple: true
            //,accept: 'file' //普通文件
            ,field: 'dypic'
            ,before: function(obj){
            }
            ,done: function(res){
              if(res.errcode){
                var html = '';
                html +='<div class="img-item">';
                if(res.count == 'file'){
                    html +='    <a href="'+ res.data +'" target="_blank"><img data-url="'+res.data+'" src="/public/static/images/pdf.png" alt=""></a>';
                }else{
                    html +='    <a href="'+ res.data +'" target="_blank"><img data-url="'+res.data+'" src="'+ res.data +'" alt=""></a>';
                }
                html +='    <i  class="layui-icon layui-icon-close-fill" onclick="imgdelete(this)"></i>';
                html +='</div>';
                
                $('#image_show').html(html)
              }
            }
        });*/

        //普通图片上传
          var uploadInst = upload.render({
            elem: '#image_up',
            url: '{:url("index/dyupload")}',
            exts: '{:config("webconfig")["cfg_upload_img_type"]}', //那么，就只会支持这三种格式的上传。注意是用|分割。
            size : {:config("webconfig")["cfg_max_img_size"]} ,//限制大小
            field: 'dypic',
            before: function(obj){
              //预读本地文件示例，不支持ie8
            
            },
            done: function(res){
              //如果上传失败
              if(res.errcode == 0){
                return layer.msg(res.message);
              }
              //上传成功
              if(res.errcode == 1){
                var is_crop = 1;
                if(is_crop == 2){
                    var html = '';
                    html +='<div class="img-item">';
                    html +='    <a href="'+ res.data +'" target="_blank"><img data-url="'+res.data+'" src="'+ res.data +'" alt=""></a>';
                    html +='    <i  class="layui-icon layui-icon-close-fill" onclick="imgdelete(this)"></i>';
                    html +='</div>';
                    
                    $('#image_show').html(html)
                    
                }else{
                    $("#cropper_image").attr("src",res.data);
                    $("#cropper_image").show();
                    // let size_str = "{if isset($vo.setup.upload_size) /}{$vo.setup.upload_size} {else/} {/if}";
                    // let arr = size_str.split("*");
                    let crop_width = "{if isset($vo.setup.upload_size_width) /}{$vo.setup.upload_size_width} {else/} 288 {/if}"
                    let crop_height = "{if isset($vo.setup.upload_size_height) /}{$vo.setup.upload_size_height} {else/} 288 {/if}"
                    layer.open({
                      type: 1,
                      title:'剪切图片',
                      area:['60%','80%'],
                      content: $('#cropper_view') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    });
                    $("#cropper_view").show();

                    var pic = "";
                    'use strict';
                    var console = window.console || { log: function () {} };
                    var URL = window.URL || window.webkitURL;
                    $image = $('#cropper_image');
                    var $dataHeight = $('#dataHeight');
                    var $dataWidth = $('#dataWidth');
                    var width = crop_width;
                    var height = crop_height;
                    var inputImageName = "";
                    if(width > 0 && height > 0){
                        var options = {
                            aspectRatio: width/height,
                            preview: '.img-preview',
                            crop: function (e) {
                                $dataHeight.val(Math.round(e.detail.height));
                                $dataWidth.val(Math.round(e.detail.width));
                            }
                        };
                    }else {
                        var options = {
                            aspectRatio: NaN,
                            preview: '.img-preview',
                            crop: function (e) {
                                $dataHeight.val(Math.round(e.detail.height));
                                $dataWidth.val(Math.round(e.detail.width));
                            }
                        };
                    }

                    var originalImageURL = $image.attr('src');
                    uploadedImageName = 'cropped.jpg';
                    uploadedImageType = 'image/jpeg';
                    var uploadedImageURL;

                    // Tooltip
                    $('[data-toggle="tooltip"]').tooltip();

                    // Cropper
                    $image.on({
                        crop: function (e) {

                        },
                        zoom: function (e) {
                            // console.log(e.type, e.detail.ratio);
                        }
                    }).cropper(options);

                    $image.cropper('destroy').attr('src', res.data).cropper(options);
                }
              }
            }
          });


        upload.render({
            elem: '#image_up2'
            ,url: "{:url('Index/dyupload')}" 
            // ,multiple: true
            //,accept: 'file' //普通文件
            ,field: 'dypic'
            ,before: function(obj){
            }
            ,done: function(res){
              if(res.errcode){
                var html = '';
                html +='<div class="img-item">';
                if(res.count == 'file'){
                    html +='    <a href="'+ res.data +'" target="_blank"><img data-url="'+res.data+'" src="/public/static/images/pdf.png" alt=""></a>';
                }else{
                    html +='    <a href="'+ res.data +'" target="_blank"><img data-url="'+res.data+'" src="'+ res.data +'" alt=""></a>';
                }
                html +='    <i  class="layui-icon layui-icon-close-fill" onclick="imgdelete(this)"></i>';
                html +='</div>';
                
                $('#image_show2').html(html)
              }
            }
        });


        //监听提交
        form.on('submit(saveBtn)', function (data) {
            var index = layer.load(1, {
                shade: [0.3,'#000'] //0.1透明度的白色背景
            });
            var data = data.field;

            var back_new_car_image=$("#image_show .img-item img").map(function(){
                    return ( $(this).attr("data-url") );
                }).get();
                data.picurl = back_new_car_image;

            var back_new_car_image2=$("#image_show2 .img-item img").map(function(){
                    return ( $(this).attr("data-url") );
                }).get();
                data.picurl2 = back_new_car_image2;
            console.log(data)
            $.ajax({
                url:"{:url('category/add')}",
                data:data,
                type:'post',
                dataType:'json',
                success:function(res){
                    layer.close(index);
                    // console.log(res)
                    // return false
                    if(res.errcode != 1){
                        layer.msg(res.message,{icon: 2,time: 2000},function(){
                            layer.close(index);
                        })
                    }else{
                        layer.msg(res.message,{icon: 1,time: 1000},function () {
                            window.location.href = "{:url('category/index')}";
                        })
                    }
                    layer.close(index);
                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('网络失败，请刷新页面后重试!',{icon: 2,time: 2000})
                }
            });

            return false;
        });

    });
</script>


<script type="text/javascript">
            // Methods
            $('.docs-buttons').on('click', '[data-method]', function () {
                console.log("tangyin")
                var $this = $(this);
                var data = $this.data();
                var cropper = $image.data('cropper');
                var cropped;
                var $target;
                var result;

                if ($this.prop('disabled') || $this.hasClass('disabled')) {
                    return;
                }

                if (cropper && data.method) {
                    data = $.extend({}, data); // Clone a new one

                    if (typeof data.target !== 'undefined') {
                        $target = $(data.target);

                        if (typeof data.option === 'undefined') {
                            try {
                                data.option = JSON.parse($target.val());
                            } catch (e) {
                                console.log(e.message);
                            }
                        }
                    }

                    cropped = cropper.cropped;

                    switch (data.method) {
                        case 'rotate':
                            if (cropped && options.viewMode > 0) {
                                $image.cropper('clear');
                            }

                            break;

                        case 'getCroppedCanvas':
                            if (uploadedImageType === 'image/jpeg') {
                                if (!data.option) {
                                    data.option = {};
                                }

                                data.option.fillColor = '#fff';
                            }

                            break;
                    }

                    result = $image.cropper(data.method, data.option, data.secondOption);

                    switch (data.method) {
                        case 'rotate':
                            if (cropped && options.viewMode > 0) {
                                $image.cropper('crop');
                            }

                            break;

                        case 'scaleX':
                        case 'scaleY':
                            $(this).data('option', -data.option);
                            break;

                        case 'getCroppedCanvas':
                            if (result) {
                                // Bootstrap's Modal
                                /*$('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
                                layer.msg('上传中..', {
                                    icon: 16
                                    ,shade: 0.3
                                    ,time: false
                                });*/
                                var file_arr = uploadedImageName.split(".")
                                var upfiles = base64toFile(result.toDataURL(uploadedImageType),file_arr[0]);
                                console.log(upfiles)
                                var formData = new FormData();
                                formData.append('dypic',upfiles);
                                $.ajax({
                                    url:"{:url('index/dyupload')}",
                                    //data: {"action":"ok","file":result.toDataURL(uploadedImageType)},
                                    //dataType:"JSON",
                                    type:"POST",
                                    data: formData,
                                    dataType: 'json',
                                    contentType: false,
                                    processData: false,
                                    beforeSend: function() {

                                    },
                                    uploadProgress: function(event, position, total, percentComplete) {

                                    },
                                    complete: function(xhr) {
                                        $(".files").html(xhr.responseText);
                                    },
                                    success: function(data) {
                                        layer.closeAll()

                                        var html = '';
                                        html +='<div class="img-item">';
                                        html +='    <a href="'+ data.data +'" target="_blank"><img data-url="'+data.data+'" src="'+ data.data +'" alt=""></a>';
                                        html +='    <i  class="layui-icon layui-icon-close-fill" onclick="imgdelete(this)"></i>';
                                        html +='</div>';
                                        
                                        $('#image_show').html(html)
                                    },
                                    error:function(xhr){
                                        layer.closeAll()
                                    }
                                })
                            }

                            break;

                        case 'destroy':
                            if (uploadedImageURL) {
                                URL.revokeObjectURL(uploadedImageURL);
                                uploadedImageURL = '';
                                $image.attr('src', originalImageURL);
                            }

                            break;
                    }

                    if ($.isPlainObject(result) && $target) {
                        try {
                            $target.val(JSON.stringify(result));
                        } catch (e) {
                            console.log(e.message);
                        }
                    }
                }
            });

            // Import image
            var $inputImage = $('#inputImage');

            if (URL) {
                $inputImage.change(function () {
                    var files = this.files;
                    var file;
                    
                    if (!$image.data('cropper')) {
                        return;
                    }

                    if (files && files.length) {
                        file = files[0];
                        
                        if (/^image\/\w+$/.test(file.type)) {
                            uploadedImageName = file.name;
                            uploadedImageType = file.type;

                            if (uploadedImageURL) {
                                URL.revokeObjectURL(uploadedImageURL);
                            }

                            uploadedImageURL = URL.createObjectURL(file);
                            $image.cropper('destroy').attr('src', uploadedImageURL).cropper(options);
                            $inputImage.val('');
                            $('.fa-search-plus').parents('button').attr('disabled',false);
                            $('.fa-search-minus').parents('button').attr('disabled',false);
                            $('.fa-check').parents('button').attr('disabled',false);
                            $('#image').show();
                        } else {
                            window.alert('Please choose an image file.');
                        }
                    }
                });
            } else {
                $inputImage.prop('disabled', true).parent().addClass('disabled');
            }


            function get_pic() {
                return pic;
            }
            //base64转为普通文件格式
            function base64toFile(dataurl, filename = 'file') {
                let arr = dataurl.split(',')
                let mime = arr[0].match(/:(.*?);/)[1]
                let suffix = mime.split('/')[1]
                let bstr = atob(arr[1])
                let n = bstr.length
                let u8arr = new Uint8Array(n)
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                }
                return new File([u8arr], `${filename}.${suffix}`, {
                    type: mime
                })
            }
            // dataUrl 转 blob
            function base64toBlob (dataurl) {
                /* eslint-disable */
                var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1];
                var bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while(n--){
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new Blob([u8arr], {type:mime});
                /* eslint-enable */
            }

        </script>

</body>
</html>